//
//  BarView.m
//  06-柱状图
//
//  Created by J on 16/2/23.
//  Copyright © 2016年 J. All rights reserved.
//

#import "BarView.h"

@implementation BarView


- (NSArray *)arrRandom
{
    int totoal = 100;
    
    NSMutableArray *arrM = [NSMutableArray array];
    
    int temp = 0; // 30 40 30
    for (int i = 0; i < arc4random_uniform(10) + 1; i++) {
        temp = arc4random_uniform(totoal) + 1;
        // 100 1~100
        
        // 随机出来的临时值等于总值，直接退出循环，因为已经把总数分配完毕，没必要在分配。
        [arrM addObject:@(temp)];
        // 解决方式：当随机出来的数等于总数直接退出循环。
        if (temp == totoal) {
            totoal -= temp;
            break;
        }
        
        totoal -= temp;

        
    }
    // 100 30 1~100
    // 70 40 0 ~ 69 1 ~ 70
    // 30 25
    // 5
    
    if (totoal) {
        [arrM addObject:@(totoal)];
    }
    
    return arrM;
}



- (void)drawRect:(CGRect)rect {
    // 06-柱状图
    
    NSArray* arr = [self arrRandom];
    
    CGFloat x = 0;
    CGFloat y = 0;
    CGFloat width = 0;
    CGFloat height = 0;

    
    for (int i=0; i<arr.count; i++) {
        width = rect.size.width/(arr.count*2-1);
        height = [arr[i] floatValue]/100.0*rect.size.height;
        x = i * width *2;
        y = rect.size.height - height ;

        UIBezierPath* path = [UIBezierPath bezierPathWithRect:CGRectMake(x, y, width, height)];
        [[self ramdomColor]set];
        [path fill];
    }
    

    
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self setNeedsDisplay];
}

- (UIColor*)ramdomColor{
    CGFloat r = arc4random_uniform(256)/255.0;
    CGFloat g = arc4random_uniform(256)/255.0;
    CGFloat b = arc4random_uniform(256)/255.0;
    return [UIColor colorWithRed:r green:g blue:b alpha:1.0];
}


@end
